'use strict';
const get = require('lodash/get');

module.exports = () =>
  async function Index(ctx, next) {
    // 从 config 中获取部分属性，放在 ctx.locals.varies 中，会通过 locals.html 定义在前端 window
    ctx.locals.varies = {};

    if (!ctx.locals.subPath || ctx.locals.subPath === '/') {
      ctx.locals.varies.urlPrefix = '';
    } else {
      ctx.locals.varies.urlPrefix = '/' + ctx.locals.subPath;
    }

    // 支持无 nginx 访问
    if (ctx.hostname === '127.0.0.1' || ctx.hostname === 'localhost') {
      const chunksMap = {};
      const chunks = ctx.locals.assets.chunks;

      for (const item in chunks) {
        if (chunks.hasOwnProperty(item)) {
          const jsArr = get(chunks, [item, 'js'], []);
          chunksMap[item] = jsArr.map((item) => `<script type="text/javascript" src="/statics/${item}"></script>`).join('');
        }
      }

      ctx.locals.chunksMap = chunksMap;
      // 直接通过 127.0.0.1 访问，urlPrefix 肯定为空
      ctx.locals.varies.urlPrefix = '';
    }

    await next();
  };
